import platform
import time
import json
import os
import random
from selenium import webdriver
from chrome_auth import get_browser_auth

KDL_PROXY_MODE = 1 # 0:usual mode 1:proxy mode
KDL_PASSWORD = 0 # username and password mode [1] or  whitelist mode [0]

KDL_WHITELIST_TUNEL = "http://tps684.kdlapi.com:15818"

HEADLESS_MODE = 1
IS_BLOCK_IMAGE = 1


#LOG_DIR = "/home/leslie/smzdm/smzdm/log"
LOG_DIR = "/Users/leslie/Desktop/smzdm/log"
#LOG_DIR = "C:/Users/leslie cheung/OneDrive/临时文件/smzdm/log"
STORE_PATH_WINDOWS = "D:/smzdm"
STORE_PATH_MAC = "/Users/leslie/Desktop/smzdm"
STORE_PATH_LINUX = "/home/leslie/smzdm/smzdm"


MAX_COMMENT_PAGES = 10
MAX_BAOLIAO_PAGES = 10
MONTHS_RANGE = 6


def  GET_PLATFORM():
    if platform.system().lower() == 'windows':
        return STORE_PATH_WINDOWS
    if platform.system().lower() == 'darwin':
        return STORE_PATH_MAC
    if platform.system().lower() == 'linux':
        return STORE_PATH_LINUX




def GET_TIME():
    return  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

def SLEEP():
    time.sleep(random.randint(1,4))
    #time.sleep(1)
    pass

def write_json(file_name,obj_dict,store_dir):
    json_str = json.dumps(obj_dict,ensure_ascii=False)
    file_obsolute_path = os.path.join(store_dir,file_name)
    #print("file : {} write success!".format(file_obsolute_path))
    with open(file_obsolute_path, 'w' , encoding='utf-8') as json_file:
        json_file.write(json_str)


def try_close_browser(browser):
    try:
        browser.close()
    except:
        pass

def try_mkdir(store_dir):
    try:
            os.mkdir(store_dir)
    except:
        pass


def get_browser(url):


    if KDL_PROXY_MODE:
        if platform.system().lower() == 'linux':
            #print("LINUX PLATFORM")
            options = webdriver.ChromeOptions()
            options.add_argument('--proxy-server={}'.format(KDL_WHITELIST_TUNEL))
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--headless')
            if IS_BLOCK_IMAGE:
                prefs = {"profile.managed_default_content_settings.images": 2}
                options.add_experimental_option("prefs", prefs)
            browser = webdriver.Chrome(options=options)
            browser.get(url)
            return browser
        else:
            options = webdriver.ChromeOptions()
            options.add_argument('--proxy-server={}'.format(KDL_WHITELIST_TUNEL))

            if HEADLESS_MODE:
                options.add_argument('--headless')

            if IS_BLOCK_IMAGE:
                prefs = {"profile.managed_default_content_settings.images": 2}
                options.add_experimental_option("prefs", prefs)

            browser = webdriver.Chrome(options=options)
            browser.get(url)
            return browser

    else:
        #print("using NONE PROXY_MODE>>>>>>>>>>>")
        browser = webdriver.Chrome()
        browser.get(url)
        return browser

def get_all_files():
    all = []
    for i in os.listdir(GET_PLATFORM()):
        try:
            if int(i.split("_")[1]):
                all.append(i.split("_")[1])
        except:
            pass
    return all

def get_random_item_url():
    folders = []
    for file in os.listdir(GET_PLATFORM()):
        #if file.split("_")[0] != "item" and len(file.split("_"))==2:
        if file.split("_")[0] == "creator" or file.split("_")[0] == "user":
            #print(file)
            folders.append(file)

    folder_choice = random.choice(folders)
    user_type = folder_choice.split("_")[0]
    folder_path = os.path.join(GET_PLATFORM(),folder_choice)
    structure_path = ""
    for file in os.listdir(folder_path):
        if len(file.split("_")) == 4 :
            structure_path = os.path.join(folder_path,file)

    with open(structure_path, 'r', encoding='utf-8') as f:
        try:
            while True:
                line = f.readline()
                if line:
                    r = json.loads(line)
                    #print(r)
                    if user_type == "user":
                        return  random.choice(r['comment_refer_item'])
                    if user_type == "creator":
                        return  random.choice(r['baoliao_url_list'])
                else:
                    break
        except:
            f.close()



if __name__ == '__main__':
    a = [get_random_item_url() for i in range(10)]
    print(a)

